/*
 * base.c - base converter
 */

#include <stdlib.h>
#include <assert.h>

#define TWO_RAISED(n) (n == 0 ? 1 : 2 << (n-1))

char *
dec2bin(long dec, int width)
{
  long i, j;
  char *bits;
  bits = malloc(width+1);
  assert(bits);
  for (i = width-1; i >= 0; i--) {
    j = TWO_RAISED(i);
    if (dec < j)
      bits[width-i-1] = '0';
    else {
      bits[width-i-1] = '1';
      dec -= j;
    }
  }
  return bits;
}

long
bin2dec(const char *bits)
{
  long dec = 0;
  while (*bits) {
    dec = dec*2 + *bits-'0';
    bits++;
  }
  return dec;
}
